/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pig4cloud.pig.common.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import sun.net.www.http.HttpClient;

/**
 * @author lengleng
 * @date 2019/2/1 RestTemplate
 */
@Configuration(proxyBeanMethods = false)
public class RestTemplateConfiguration {

	@Bean
	public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
		// boot中可使用RestTemplateBuilder.build创建
		RestTemplate restTemplate = new RestTemplate();
		// 配置请求工厂
		restTemplate.setRequestFactory(clientHttpRequestFactory);
		return restTemplate;
	}


	/**
	 * 请求连接池配置
	 * @param httpClient
	 * @return
	 */
	@Bean
	public ClientHttpRequestFactory clientHttpRequestFactory(/*HttpClient httpClient*/) {
		HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
		// httpClient创建器（暂时用默认的吧）
		//clientHttpRequestFactory.setHttpClient(httpClient);
		// 连接超时时间/毫秒（连接上服务器(握手成功)的时间，超出抛出connect timeout）
		clientHttpRequestFactory.setConnectTimeout(5 * 1000);
		// 数据读取超时时间(socketTimeout)/毫秒（务器返回数据(response)的时间，超过抛出read timeout）
		clientHttpRequestFactory.setReadTimeout(10 * 1000);
		// 连接池获取请求连接的超时时间，不宜过长，必须设置/毫秒（超时间未拿到可用连接，会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool）
		clientHttpRequestFactory.setConnectionRequestTimeout(5 * 1000);
		return clientHttpRequestFactory;
	}

	/**
	 * HttpClient
	 * @param poolingHttpClientConnectionManager
	 * @return
	@Bean
	public HttpClient httpClient(HttpClientConnectionManager poolingHttpClientConnectionManager) {
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// 设置http连接管理器
		httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);

		// 设置重试次数
		//httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

		// 设置默认请求头
		//List<Header> headers = new ArrayList<>();
		//headers.add(new BasicHeader("Connection", "Keep-Alive"));
		//httpClientBuilder.setDefaultHeaders(headers);

		return httpClientBuilder.build();
	}
	 */

}
